package com.naiterui.ehp.bs.cms.common.utils;

import cn.hutool.json.JSONUtil;
import com.naiterui.ehp.bp.support.exception.BusinessException;
import com.naiterui.ehp.bp.utils.lang.ConfigUtil;
import com.naiterui.ehp.bs.cms.common.exception.BusinessExceptionCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * 腾讯云ocr识别
 *
 * @author yangfuya
 * @version 1.0
 * @date 2021/4/21 16:07
 **/
@Slf4j
public class OcrUtil {
    private static final String APPCODE = ConfigUtil.getString("aliyun.ocr.appcode");
    private static final String ID_CARD_HOST = ConfigUtil.getString("aliyun.ocr.id-card.host");
    private static final String ID_CARD_PATH = ConfigUtil.getString("aliyun.ocr.id-card.path");
    private static final String ID_CARD_METHOD = ConfigUtil.getString("aliyun.ocr.id-card.method");
    private static final String CUSTOMIZE_HOST = ConfigUtil.getString("aliyun.ocr.customize.host");
    private static final String CUSTOMIZE_PATH = ConfigUtil.getString("aliyun.ocr.customize.path");
    private static final String CUSTOMIZE_METHOD = ConfigUtil.getString("aliyun.ocr.customize.method");
    private static final String CUSTOMIZE_QUALIFICATIONS = ConfigUtil.getString("aliyun.ocr.customize.qualifications");
    private static final String CUSTOMIZE_PRACTICE = ConfigUtil.getString("aliyun.ocr.customize.practice");

    /**
     * 身份证识别
     *
     * @param imageBase64 身份证的base64值
     * @return 身份证号
     * @throws BusinessException /
     */
    public static String idCardDistinguish(String imageBase64) throws BusinessException {
        JSONObject configure = new JSONObject();
        configure.put("side", "face");
        // 拼装请求body的json字符串
        JSONObject requestObj = new JSONObject();
        requestObj.put("image", imageBase64);
        requestObj.put("configure", configure);
        String bodys = requestObj.toString();
        try {
            log.info("orc id card host: {}, path: {}, method: {}, configure: {}", ID_CARD_HOST, ID_CARD_PATH, ID_CARD_METHOD, configure.toString());
            HttpResponse response = HttpUtils.doPost(ID_CARD_HOST, ID_CARD_PATH, ID_CARD_METHOD, generateHeader(), Collections.emptyMap(), bodys);
            int stat = response.getStatusLine().getStatusCode();
            if (stat != HttpStatus.SC_OK) {
                log.error("http code: {}, Http header error msg: {}, Http body error msg: {}", stat, response.getFirstHeader("X-Ca-Error-Message"), EntityUtils.toString(response.getEntity()));
                throw new BusinessException(BusinessExceptionCode.OCR_ERROR, "ocr识别身份证失败");
            }
            String res = EntityUtils.toString(response.getEntity());
            log.info("ocr idCare result: {}", res);
            JSONObject resJson = new JSONObject(res);
            if (resJson.has("num")) {
                return resJson.getString("num");
            }
            return "";
        } catch (Exception e) {
            e.printStackTrace();
            log.error("exception: {}", e.getMessage());
            throw new BusinessException(BusinessExceptionCode.OCR_ERROR, "ocr识别身份证失败");
        }
    }

    /**
     * 自定义模板识别
     *
     * @param imageBase64 图片的base64值
     * @return 证书编号
     * @throws BusinessException /
     */
    public static String customizeDistinguish(String imageBase64) throws BusinessException {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("image", imageBase64);
        String[] templates = {CUSTOMIZE_QUALIFICATIONS, CUSTOMIZE_PRACTICE};
        JSONObject configure = new JSONObject();
        configure.put("template_list", templates);
        jsonObject.put("configure", configure);
        try {
            log.info("orc customize host: {}, path: {}, method: {}, configure: {}", CUSTOMIZE_HOST, CUSTOMIZE_PATH, CUSTOMIZE_METHOD, configure.toString());
            HttpResponse response = HttpUtils.doPost(CUSTOMIZE_HOST, CUSTOMIZE_PATH, CUSTOMIZE_METHOD, generateHeader(), Collections.emptyMap(), jsonObject.toString());
            int stat = response.getStatusLine().getStatusCode();
            if (stat != HttpStatus.SC_OK) {
                log.error("http code: {}, Http header error msg: {}, Http body error msg: {}", stat, response.getFirstHeader("X-Ca-Error-Message"), EntityUtils.toString(response.getEntity()));
                throw new BusinessException(BusinessExceptionCode.OCR_ERROR, "ocr识别失败");
            }
            String res = EntityUtils.toString(response.getEntity());
            log.info("ocr customize result: {}", res);
            JSONObject resJson = new JSONObject(res);
            if (resJson.has("items")) {
                JSONObject items = resJson.getJSONObject("items");
                String number = null;
                if (items.has("number")) {
                    number = items.getString("number");
                    if (items.has("number1")) {
                        number = number + items.getString("number1");
                    }
                }
                return number;
            }
            return "";
        } catch (Exception e) {
            e.printStackTrace();
            log.error("exception: {}", e.getMessage());
            throw new BusinessException(BusinessExceptionCode.OCR_ERROR, "ocr识别失败");
        }
    }

    /**
     * 生成header
     *
     * @return headers
     */
    private static Map<String, String> generateHeader() {
        Map<String, String> headers = new HashMap<>(5);
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + APPCODE);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/json; charset=UTF-8");

        log.info("ocr header: {}", JSONUtil.toJsonStr(headers));
        return headers;
    }
}
